package utils

import (
	"center-platform/config"
	"errors"
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

type Auth struct {
	UserId int
	Email  string
}

type Claims struct {
	UserId int
	Email  string
	jwt.RegisteredClaims
}

var jwtKey = []byte(config.GlobalConfig.Http.JwtKey)

func (a *Auth) GenerateToken() (string, error) {
	claim := Claims{
		UserId: a.UserId,
		Email:  a.Email,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 2)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenStr, err := token.SignedString(jwtKey)

	return tokenStr, err
}

func ParseToken(tokenStr string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	if err != nil {
		fmt.Println("token parse err :", err.Error())
	}

	if claim, ok := token.Claims.(*Claims); ok && token.Valid {
		return claim, nil
	}
	return nil, errors.New("invalid token")
}
